<?php 
namespace app\wework\controller\job;

use app\BaseController;
use think\facade\Db;
use app\wework\model\Helper;
use app\wework\model\BaseModel;
use app\wework\model\user\send\GroupSendModel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use think\queue\Job;
use app\wework\controller\Base;


/**
* 定时任务，实时发送提醒
*/
class BuffetPromotion extends BaseController{
	public function index(){
		$config_list = Db::table('kt_wework_config')->where(["customer_status"=>1])->column("wid");
		if(!$config_list) return success("操作失败");
		foreach ($config_list as $wid) {
			$this->promotion($wid);
		}

		return success("操作成功");
	}

	public function promotion($wid){
		$time = date("Y-m-d"); 
		$promotions = Db::table("kt_wework_promotion")->where(["wid"=>$wid,"status"=>1])->json(["staffs"])->select()->toArray();
		foreach($promotions as $value){
			$status = Db::table("kt_wework_promotion_status")->find(["wid"=>$wid,"pid"=>$value["id"]])->whereTime("ctime",">=",$time)->find();
			if($status)continue;
			if(strtotime($value["ttime"]) >= time()){
				foreach ($value["staffs"] as $staff_id){
					$staff = Db::table("kt_wework_staff")->where(["id"=>$staff_id])->find();
					$add_size = Db::table("kt_wework_promotion_size")->where(["type"=>2,"pid"=>$value["id"],"staff_id"=>$staff_id])->count();
					$del_size = Db::table("kt_wework_promotion_size")->where(["type"=>3,"pid"=>$value["id"],"staff_id"=>$staff_id])->count();
					$addsize = Db::table("kt_wework_promotion_size")->where(["type"=>2,"pid"=>$value["id"],"staff_id"=>$staff_id])->whereTime("ctime",">=",$time)->count();
					$delsize = Db::table("kt_wework_promotion_size")->where(["type"=>3,"pid"=>$value["id"],"staff_id"=>$staff_id])->whereTime("ctime",">=",$time)->count();
					if($value["type"] == 1){
						$str = "【推广提醒】";
						$str .= "<br>";
						$str .= "<br>";
						$str .= "截止目前，您已成功添加".$add_size."个客户，其中".$del_size."个已流失";
						$str .= "<br>";
						$str .= "<br>";
						$str .= "今日已添加客户数：".$addsize."个！";
						$str .= "<br>";
						$str .= "<br>";
						$str .= "今日已流失客户数：".$delsize."个！";
					}else{
						$str = "【推广提醒】";
						$str .= "<br>";
						$str .= "<br>";
						$str .= "截止目前，您已成功邀请".$add_size."个客户入群，其中".$del_size."个已经退群";
						$str .= "<br>";
						$str .= "<br>";
						$str .= "今日已入群客户数：".$addsize."个！";
						$str .= "<br>";
						$str .= "<br>";
						$str .= "今日已退群客户数：".$delsize."个！";
					}
					$res = QyWechatApi::sendText($wid,$staff["userid"],$str);
				}
			}
			$status["wid"] = $wid;
			$status["pid"] = $value["id"];
			$status["time"] = date("Y-m-d H:i:s");
			Db::table("kt_wework_promotion_status")->insertGetId($status);
		}
	}
}